import { Prefab, resources, instantiate, director, AudioSource, AudioClip } from "cc";
import { ResourceDefine } from "../resource/ResourceDefine";
import { Setting } from "../config/Setting";

export class AudioManager{

  private static _instance: AudioManager;

  static get instance():AudioManager{
   if(this._instance == null){
       this._instance = new AudioManager();
   }
   return this._instance;
  }


  bgm: AudioSource = null;
  sfx: AudioSource = null;
  private readonly sfxClip: Map<string, AudioClip> = new Map()

  hitClip: AudioClip = null;
  shotClip: AudioClip = null;

  init(){
    this.loadResource();
  }

  destroy(){
    this.bgm = null;
    this.sfx = null;
    this.hitClip = null;
    this.shotClip = null;
  }


  loadResource(){
    // resources.load(ResourceDefine.BgmPath, Prefab, (err:Error, prefab:Prefab)=>{
    //   if(err){
    //     throw err;
    //   }
    //   let node = instantiate(prefab);
    //   director.getScene().addChild(node);
    //   this.bgm = node.getComponent(AudioSource);
    //   this.bgm.volume = Setting.instance.bgmVolume;
    // })

    resources.load(ResourceDefine.SfxPath, Prefab, (err:Error, prefab:Prefab)=>{
      let node = instantiate(prefab);
      director.getScene().addChild(node);
      this.sfx = node.getComponent(AudioSource);
      this.sfx.volume = Setting.instance.sfxVolume;
    })

    this.initSfx(ResourceDefine.ShootClip);
    this.initSfx(ResourceDefine.HitClip);
  }

  private initSfx(path: string) {
    resources.load(path, AudioClip, (err: Error, clip: AudioClip) => {
        this.sfxClip.set(path, clip);
    });
  }


  private playSfx(path: string) {
    if (!this.sfxClip.has(path)) {
        return;
    }
    let clip = this.sfxClip.get(path);
    let audioSource = this.sfx.getComponent(AudioSource);
    audioSource.clip = clip;
    audioSource.volume = Setting.instance.sfxVolume;
    audioSource.play()
    
  }

  playHitSfx()
  {
    this.playSfx(ResourceDefine.HitClip);
  }

  playShootSfx()
  {
    this.playSfx(ResourceDefine.ShootClip);
  }

}